package com.small.nacos.core.cluster;

import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.small.nacos.sys.env.EnvUtil;
import com.small.nacos.sys.utils.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author zhoujin
 * @Date 2022/11/5 10:36
 */
public class MemberUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(MemberUtil.class);

    protected static final String TARGET_MEMBER_CONNECT_REFUSE_ERRMSG = "Connection refused";

    public static Member singleParse(String member) {
        // Nacos default port is 8848
        int defaultPort = 8848;
        // Set the default Raft port information for securit

        String address = member;
        int port = defaultPort;
        String[] info = IPUtil.splitIPPortStr(address);
        if (info.length > 1) {
            address = info[0];
            port = Integer.parseInt(info[1]);
        }

        Member target = Member.builder().ip(address).port(port).state(NodeState.UP).build();

        return target;
    }

    public static List<String> simpleMembers(Collection<Member> members) {
        return members.stream().map(Member::getAddress).sorted()
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    }


    public static Set<Member> selectTargetMembers(Collection<Member> members, Predicate<Member> filter) {
        return members.stream().filter(filter).collect(Collectors.toSet());
    }

    public static Collection<Member> readServerConf(Collection<String> members) {
        Set<Member> nodes = new HashSet<>();

        for (String member : members) {
            Member target = singleParse(member);
            nodes.add(target);
        }
        return nodes;
    }

    public static void syncToFile(Collection<Member> members) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("#").append(LocalDateTime.now()).append(StringUtils.LF);
            for (String member : simpleMembers(members)) {
                builder.append(member).append(StringUtils.LF);
            }
            EnvUtil.writeClusterConf(builder.toString());
        } catch (Throwable ex) {
            LOGGER.error("cluster member node persistence failed : {}", ExceptionUtil.getAllExceptionMsg(ex));
        }
    }

    public static void onSuccess(final ServerMemberManager manager, final Member member) {
        final NodeState old = member.getState();
        member.setState(NodeState.UP);
        member.setFailAccessCnt(0);
        if (!Objects.equals(old, member.getState())) {
            manager.notifyMemberChange();
        }
    }

    public static void onFail(final ServerMemberManager manager, final Member member) {
        // To avoid null pointer judgments, pass in one NONE_EXCEPTION
        onFail(manager, member, ExceptionUtil.NONE_EXCEPTION);
    }

    public static void onFail(final ServerMemberManager manager, final Member member, Throwable ex) {

        final NodeState old = member.getState();
        member.setState(NodeState.SUSPICIOUS);
        member.setFailAccessCnt(member.getFailAccessCnt() + 1);
        int maxFailAccessCnt = EnvUtil.getProperty("nacos.core.member.fail-access-cnt", Integer.class, 3);

        // If the number of consecutive failures to access the target node reaches
        // a maximum, or the link request is rejected, the state is directly down
        if (member.getFailAccessCnt() > maxFailAccessCnt || StringUtils
                .containsIgnoreCase(ex.getMessage(), TARGET_MEMBER_CONNECT_REFUSE_ERRMSG)) {
            member.setState(NodeState.DOWN);
        }
        if (!Objects.equals(old, member.getState())) {
            manager.notifyMemberChange();
        }
    }

    public static boolean isBasicInfoChanged(Member actual, Member expected) {
        if (null == expected) {
            return null == actual;
        }
        if (!expected.getIp().equals(actual.getIp())) {
            return true;
        }
        if (expected.getPort() != actual.getPort()) {
            return true;
        }
        if (!expected.getAddress().equals(actual.getAddress())) {
            return true;
        }
        if (!expected.getState().equals(actual.getState())) {
            return true;
        }
        return false;
    }

    public static void copy(Member newMember, Member oldMember) {
        oldMember.setIp(newMember.getIp());
        oldMember.setPort(newMember.getPort());
        oldMember.setState(newMember.getState());
        oldMember.setFailAccessCnt(newMember.getFailAccessCnt());
        oldMember.setAddress(newMember.getAddress());
    }
}
